from django.middleware.common import CommonMiddleware
from django.http import JsonResponse
from django_system.settings import SECRET_KEY
import jwt


class TokenMiddleware(CommonMiddleware):
    def __call__(self, request):
        if request.path != '/login/' and request.path != '/register/' and request.path != '/user/users/':
            try:
                token = request.META.get('HTTP_AUTHORIZATION', None).split(' ')[1]
            except:
                return JsonResponse({'error': 'Token invalido'}, status=401)
            if token:
                try:
                    payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
                    user = payload['user']
                    if user:
                        request.user = user
                except jwt.ExpiredSignatureError:
                    return JsonResponse({'error': 'Token invalido'}, status=401)
                except jwt.InvalidTokenError:
                    return JsonResponse({'error': 'Token invalido'}, status=401)
        return super().__call__(request)

